package ru.aslanov.schedule.server;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * Created: Nov 25, 2009 3:56:12 PM
 *
 * @author Sergey Aslanov
 */
public class PMF {
    private static final Logger log = Logger.getLogger(PMF.class.getName());

    private static final PersistenceManagerFactory pmfInstance =
        JDOHelper.getPersistenceManagerFactory("transactions-optional");

    private static ThreadLocal<PersistenceManager> persistenceManagerThreadLocal = new InheritableThreadLocal<PersistenceManager>();

    private PMF() {}

    public static PersistenceManagerFactory get() {
        return pmfInstance;
    }

    public static PersistenceManager getThreadLocalPersistenceManager() {
        PersistenceManager pm = persistenceManagerThreadLocal.get();
        if (pm == null) {
            log.fine("Opening persistence manager");
            pm = get().getPersistenceManager();
            persistenceManagerThreadLocal.set(pm);
        }
        return pm;
    }

    public static void closeThreadLocalPersistenceManager() {
        final PersistenceManager pm = persistenceManagerThreadLocal.get();
        if (pm != null) {
            log.fine("Closing persistence manager");
            pm.close();
            persistenceManagerThreadLocal.remove();
        }
    }
}
